<template>
  <el-cascader
    v-loading="loading && isNotInCommonForm"
    element-loading-spinner="el-icon-loading"
    size="small"
    v-model="data"
    :style="style"
    v-bind="$attrs"
    :options="selectOptions"
    @change="handleChange"
    :props="{
      checkStrictly: multiple,
      value: 'id',
      label: 'name',
      children: 'child'
    }"
    clearable
  />
</template>

<script>
export default {
  props: {
    value: {
      type: [Array, String]
    },
    query: {
      type: String,
      default: ""
    },
    multiple: {
      type: Boolean,
      default: true
    },
    isNotInCommonForm: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: "200px"
    },
    autoQuery: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    style() {
      return {
        width: this.width
      }
    }
  },
  created() {
    if (this.query && this.autoQuery) {
      this.$ajax.get(this.query).then((res) => {
        this.selectOptions = res.data
      })
    }
  },
  data() {
    return {
      data: this.value,
      selectOptions: [],
      loading: false
    }
  },
  watch: {
    value(val) {
      this.data = val
    },
    query(val) {
      if (val) {
        this.queryArea()
      }
    }
  },
  methods: {
    queryArea() {
      this.loading = true
      this.$ajax.get(this.query).then((res) => {
        this.selectOptions = res.data
        this.$nextTick(() => {
          this.loading = false
        })
      })
    },
    handleChange(val) {
      this.$emit("input", val)
    }
  }
}
</script>
